import { baseUrl } from '../utils/baseUrl';

export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';

// 获取当前认证token的函数
function getAuthToken(): string | null {
  // 从localStorage获取token（如果使用localStorage）
  const token = localStorage.getItem('authToken');
  if (token) return token;
  
  // 从sessionStorage获取token（如果使用sessionStorage）
  const sessionToken = sessionStorage.getItem('authToken');
  if (sessionToken) return sessionToken;
  
  // 从全局状态获取token（如果使用状态管理）
  // 这里可以集成Recoil或其他状态管理库
  return null;
}

// 在开发环境中使用代理，在生产环境中使用完整URL
const BASE_URL = import.meta.env.DEV ? '' : baseUrl;

export async function request<T>(path: string, options: {
  method?: HttpMethod;
  headers?: Record<string, string>;
  query?: Record<string, string | number | boolean | undefined | null>;
  body?: any;
  token?: string;
  useFormData?: boolean; // 新增参数，用于控制是否使用表单数据格式
} = {}): Promise<T> {
  const { method = 'GET', headers = {}, query, body, useFormData = false } = options;
  
  // 自动获取token，优先使用传入的token，否则从存储中获取
  const authToken = options.token || getAuthToken();
  
  // 构建完整的URL
  const fullUrl = BASE_URL ? `${BASE_URL}${path}` : path;
  const url = new URL(fullUrl, window.location.origin);
  
  // 开发环境下打印 URL 构建信息
  if (import.meta.env.DEV) {
    console.log('URL构建信息:', {
      BASE_URL,
      path,
      fullUrl,
      finalUrl: url.toString(),
      windowLocation: window.location.origin
    });
  }
  
  if (query) {
    Object.entries(query).forEach(([k, v]) => {
      if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
    });
  }
  // 处理请求体和Content-Type
  let requestBody: string | FormData | undefined;
  let contentType: string;
  
  if (body) {
    if (useFormData) {
      // 使用表单数据格式
      const formData = new URLSearchParams();
      Object.entries(body).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          formData.append(key, String(value));
        }
      });
      requestBody = formData.toString();
      contentType = 'application/x-www-form-urlencoded';
    } else {
      // 使用JSON格式
      requestBody = JSON.stringify(body);
      contentType = 'application/json';
    }
  } else {
    requestBody = undefined;
    contentType = 'application/json';
  }

  // 开发环境下打印请求信息
  if (import.meta.env.DEV) {
    const requestHeaders = {
      'Accept': 'application/json, text/javascript, */*; q=0.01',
      'Accept-Language': 'zh-CN,zh;q=0.9,fa;q=0.8,en;q=0.7',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Content-Type': contentType,
      'Origin': window.location.origin,
      'Pragma': 'no-cache',
      'Referer': window.location.href,
      'Sec-Fetch-Dest': 'empty',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Site': 'same-origin',
      'User-Agent': navigator.userAgent,
      'X-Requested-With': 'XMLHttpRequest',
      ...(authToken ? { 'Authorized-Token': authToken } : {}),
      ...headers,
    };
    
    console.log('API Request:', {
      url: url.toString(),
      method,
      headers: requestHeaders,
      body: requestBody,
      useFormData,
    });
    
    // 检查是否是代理请求
    if (url.toString().includes('localhost') && path.startsWith('/api')) {
      console.log('🔍 这是代理请求，应该转发到后端服务器');
    }
  }

  const res = await fetch(url.toString(), {
    method,
    headers: {
      'Accept': 'application/json, text/javascript, */*; q=0.01',
      'Accept-Language': 'zh-CN,zh;q=0.9,fa;q=0.8,en;q=0.7',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Content-Type': contentType,
      'Origin': window.location.origin,
      'Pragma': 'no-cache',
      'Referer': window.location.href,
      'Sec-Fetch-Dest': 'empty',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Site': 'same-origin',
      'User-Agent': navigator.userAgent,
      'X-Requested-With': 'XMLHttpRequest',
      ...(authToken ? { 'Authorized-Token': authToken } : {}),
      ...headers,
    },
    body: requestBody,
    credentials: 'include',
  });
  // 先获取文本内容，然后尝试解析JSON
  const text = await res.text();
  
  // 开发环境下打印响应信息
  if (import.meta.env.DEV) {
    const headersObj: Record<string, string> = {};
    res.headers.forEach((value, key) => {
      headersObj[key] = key;
    });
    console.log('🔍 API响应信息:', {
      status: res.status,
      statusText: res.statusText,
      headers: headersObj,
      responseText: text
    });
  }
  
  // 尝试解析JSON响应
  try {
    const data = JSON.parse(text) as any;

    // 检查业务逻辑错误：code 不等于 0 且不等于 200 且不等于 '200' 表示失败
    if (data && typeof data === 'object' && 'code' in data && 
        data.code !== 0 && data.code !== 200 && data.code !== '200') {
      return Promise.reject(data);
    }
    
    return data as T;
  } catch (parseError) {
    // 如果JSON解析失败，检查是否是HTTP错误
    if (!res.ok) {
      let errorMessage = `HTTP ${res.status}`;
      
      // 尝试解析错误信息
      if (text) {
        // 如果是 HTML 错误页面，尝试提取错误信息
        if (text.includes('<title>')) {
          const titleMatch = text.match(/<title>([^<]+)<\/title>/);
          if (titleMatch) {
            errorMessage = titleMatch[1];
          }
        } else {
          // 如果不是 JSON，使用原始文本（截取前100个字符）
          errorMessage = text.length > 100 ? text.substring(0, 100) + '...' : text;
        }
      }
      
      throw new Error(errorMessage);
    }
    
    // 如果JSON解析失败但不是HTTP错误，记录错误并抛出
    console.error('JSON解析失败:', parseError, '响应内容:', text);
    throw new Error(`响应解析失败: ${text.substring(0, 100)}`);
  }
}

// 便捷的HTTP方法
export const get = <T>(path: string, query?: Record<string, any>, options?: { isDisLoading?: boolean; token?: string }) => {
  return request<T>(path, { method: 'GET', query, token: options?.token });
};

export const post = <T>(path: string, body?: any, options?: { isDisLoading?: boolean; useFormData?: boolean; token?: string }) => {
  return request<T>(path, { method: 'POST', body, useFormData: options?.useFormData, token: options?.token });
};

export const put = <T>(path: string, body?: any, options?: { isDisLoading?: boolean; useFormData?: boolean }) => {
  return request<T>(path, { method: 'PUT', body, useFormData: options?.useFormData });
};

export const del = <T>(path: string, options?: { isDisLoading?: boolean }) => {
  return request<T>(path, { method: 'DELETE' });
};



